package ${module.package};

import ${daoModule.package}.${table.beanName}Dao;
import ${dtoModule.package}.${table.beanName}Request;
import ${dtoModule.package}.${table.beanName}Response;
import ${beanModule.package}.${table.beanName}Bean;
import com.cellulam.framework.core.utils.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ${table.enablePrimitiveType?string('com.cellulam.framework.datasource.service.BaseSimpleDtoService','com.cellulam.framework.datasource.service.BaseDtoService')};

<#if table.hasUniqKey()>
import java.util.function.Consumer;
import java.util.function.Function;
</#if>

/**
 * service for ${table.beanName} <br>
 * Created by ${loginUser} on ${generateDate}.
 */
@Service
public class ${table.beanName}Service extends ${table.enablePrimitiveType?string('BaseSimpleDtoService','BaseDtoService')}<${table.pk.wrapperFieldType.simpleName}, ${table.beanName}Bean, ${table.beanName}Request, ${table.beanName}Response> {

    @Autowired
    private ${table.beanName}Dao ${table.beanName?uncap_first}Dao;

    /**
     * 保存<code>request</code>
     * @param request
     * @return 新增的数据的行主键(如果主键是自增)
     */
    public ${table.pk.fieldType.simpleName} save(${table.beanName}Request request) {
        ${table.beanName}Bean bean = BeanUtil.copy(request, ${table.beanName}Bean.class);
        saveBean(bean);
        request.set${table.pk.fieldName?cap_first}(bean.get${table.pk.fieldName?cap_first}());
        return bean.get${table.pk.fieldName?cap_first}();
    }

    <#if table.generateDel()>

    <#if table.hasUpdateUser()>
    /**
     * 删除
     * @param id
     * @param userId
     * @return 删除是否成功
     */
    public boolean delete(${table.pk.fieldType.simpleName} id, int userId) {
        return ${table.beanName?uncap_first}Dao.delete(id, userId) > 0;
    }
    <#else>
    /**
     * 删除
     * @param id
     * @return 删除是否成功
     */
    public boolean delete(${table.pk.fieldType.simpleName} id) {
        return ${table.beanName?uncap_first}Dao.delete(id) > 0;
    }
    </#if>
    </#if>

<#if table.hasUniqKey()>

    /**
     * 锁行执行
     *
     * @param consumer
     */
    public void lockForExecute(${table.uniqKeyParams}, Consumer<${table.beanName}Bean> consumer) {
        this.executeInTran(() -> {
        ${table.beanName}Bean bean = this.getCrudDao().lockByKey(${table.uniqKeyParamsNoType});
            consumer.accept(bean);
        });
    }

    /**
     * 锁行执行，带返回值
     *
     * @param function
     * @param <T>
     * @return
     */
    public <T> T lockForSubmit(${table.uniqKeyParams}, Function<${table.beanName}Bean, T> function) {
        return this.commitInTran(() -> {
        ${table.beanName}Bean bean = this.getCrudDao().lockByKey(${table.uniqKeyParamsNoType});
            return function.apply(bean);
        });
    }
</#if>
    protected ${table.beanName}Dao getCrudDao() {
        return ${table.beanName?uncap_first}Dao;
    }
}
